package com.zhoulz.homework.chaptor02;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.utils.CloseableUtils;
import org.apache.log4j.Logger;

import com.zhoulz.homework.chaptor02.config.Config;
import com.zhoulz.homework.chaptor02.node.Server;
import com.zhoulz.homework.chaptor02.zk.Zk;

/**
 * 启动节点程序主入口
 */
public class App 
{
	static Logger log = Logger.getLogger(App.class);
	private static String host;
	private static String port;
	private static String keepAlive;
    public static void main( String[] args )
    {
    	//Assert.assertTrue("请通过参数传入节点名", args.length > 0);
    	final String nodeName = args[0];
    	
    	Config.load(Config.LOCAL_CONFIG_NAME);
        CuratorFramework client = null;
        try {
        	String connectionString = String.format("%s:%s", 
        			Config.get(Config.KEY_ZK_SERVER_IP), 
        			Config.get(Config.KEY_ZK_SERVER_PORT));
			client = Zk.newClient(connectionString);
        	client.start();
        	if(client.getZookeeperClient().blockUntilConnectedOrTimedOut()){
        		Zk.init(client, nodeName);
        	}else{
        		log.info(String.format("连接zk server(%s:%s)失败, 使用本地配置.", 
        				Config.get(Config.KEY_ZK_SERVER_IP),
        				Config.get(Config.KEY_ZK_SERVER_PORT)));
        		
        		Config.load(Config.LOCAL_LEADER_CONFIG_NAME);
        	}
        	host = Config.get(Config.KEY_TCP_HOST_IP);
        	port = Config.get(Config.KEY_TCP_HOST_PORT);
        	keepAlive = Config.get(Config.KEY_TCP_KEEPALIVE);
        	
        	// 启动服务
        	Server server = new Server(nodeName, 
        			host, 
        			Integer.parseInt(port), 
        			"1".equals(keepAlive)? true : false);
        	server.start(client);
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			CloseableUtils.closeQuietly(client);
		}
    }
}
